package com.qb.square.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.CacheDiskStaticUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.qb.baselibrary.basekotlin.EmptyViewModel
import com.qb.common.base.CommonBaseFragment
import com.qb.common.bean.UserInfo
import com.qb.common.constant.Constants
import com.qb.common.router.RouterPath
import com.qb.common.utils.LitePalUtils
import com.qb.common.utils.ValidUtils
import com.qb.square.R
import com.qb.square.databinding.SquareFragmentBinding
import java.io.File


/**
 * @ClassName: SquareFragment
 * @Description: Description
 * @Author: qq
 * @Date: 2022/9/28 18:03
 */
@Route(path = RouterPath.Square.URL_Square_MainFragment)
class SquareFragment:CommonBaseFragment<EmptyViewModel,SquareFragmentBinding>(), View.OnClickListener {
    var isPush = false
    var loginInfo = ""
    var userInfo:UserInfo? = null
    companion object{
        @SuppressLint("SquareFragment")
        private var instance:SquareFragment?=null
        @Synchronized
        fun get():SquareFragment{
            if (null== instance) instance = SquareFragment()
            return instance as SquareFragment
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        mBinding.userAvatar.setOnClickListener(this)
        mBinding.userName.setOnClickListener(this)
        mBinding.personalCenter.setOnClickListener(this)
        mBinding.settings.setOnClickListener(this)
        mBinding.about.setOnClickListener(this)
        mBinding.ivPush.setOnClickListener(this)
        mBinding.tvLogout.setOnClickListener(this)
        mBinding.llZxzh.setOnClickListener(this)
        mBinding.tvJl.setOnClickListener(this)

        isPush = SPStaticUtils.getBoolean(Constants.isPush)
        mBinding.ivPush.setBackgroundResource(R.drawable.icon_switch_close)
        if (isPush){
            mBinding.ivPush.setBackgroundResource(R.drawable.icon_switch_open)
        }
    }

    override fun onResume() {
        super.onResume()
        loginInfo = SPStaticUtils.getString(Constants.LOGININFO)
        if (TextUtils.isEmpty(loginInfo)){
            mBinding.userName.text = "请登录"
        }else{
            userInfo = GsonUtils.fromJson<UserInfo>(loginInfo,UserInfo::class.java)
            mBinding.userName.text = userInfo?.username
            if (ValidUtils.isValid(userInfo?.avater)){
                Glide.with(this).load(File(userInfo?.avater)).into(mBinding.userAvatar)
            }
        }
    }

    override fun onClick(v: View?) {
        v?.let {
            when(v.id){
                mBinding.userName.id->{
                    if (TextUtils.isEmpty(loginInfo)){
                        ARouter.getInstance().build(RouterPath.Login.URL_Login_LoginActivity).navigation()
                    }else{
                        ToastUtils.showShort("您已登录")
                    }
                }
                mBinding.userAvatar.id->{
                    if (TextUtils.isEmpty(loginInfo)){
                        ARouter.getInstance().build(RouterPath.Login.URL_Login_LoginActivity).navigation()
                    }else{
                        XXPermissions.with(mContext)
                            .permission(Permission.Group.STORAGE)
                            .request(object :OnPermissionCallback{
                                override fun onGranted(
                                    permissions: MutableList<String>?,
                                    all: Boolean
                                ) {
                                    if (all){
                                        PictureSelector.create(activity)
                                            .openSystemGallery(SelectMimeType.ofImage())
                                            .forSystemResult(object : OnResultCallbackListener<LocalMedia?> {
                                                override fun onResult(result: ArrayList<LocalMedia?>) {
                                                    LogUtils.e("输出选择图片结果："+result[0]?.realPath)
                                                    if (ValidUtils.isValid(result)){
                                                        if (ValidUtils.isValid(userInfo)){
                                                            userInfo?.avater = "${result[0]?.realPath}"
                                                            userInfo?.save()
                                                            SPStaticUtils.put(Constants.LOGININFO,GsonUtils.toJson(userInfo))
                                                        }
                                                        activity?.let { it1 -> Glide.with(it1).load(File(result[0]?.realPath)).placeholder(R.mipmap.app_kuaikan).into(mBinding.userAvatar) }
                                                    }
                                                }
                                                override fun onCancel() {}
                                            })
                                    }
                                }

                            })


                    }
                }
                mBinding.personalCenter.id,mBinding.ivPush.id->{
                    if (isPush){
                        isPush = false
                        SPStaticUtils.put(Constants.isPush,false)
                        mBinding.ivPush.setBackgroundResource(R.drawable.icon_switch_close)
                        ToastUtils.showShort("推送关闭")
                    }else{
                        isPush = true
                        SPStaticUtils.put(Constants.isPush,true)
                        mBinding.ivPush.setBackgroundResource(R.drawable.icon_switch_open)
                        ToastUtils.showShort("推送开启")
                    }
                }
                mBinding.settings.id->{
                    CacheDiskStaticUtils.clear()
                    userInfo?.avater = ""
                    userInfo?.save()
                    SPStaticUtils.put(Constants.LOGININFO,GsonUtils.toJson(userInfo))
                    Glide.with(this).load(userInfo?.avater).placeholder(R.mipmap.app_kuaikan).into(mBinding.userAvatar)
                    ToastUtils.showShort("清理缓存成功")
                }
                mBinding.about.id->{
                    ToastUtils.showShort("当前系统版本${AppUtils.getAppVersionName()}")
                }
                mBinding.tvLogout.id->{
                    if (ValidUtils.isValid(userInfo)){
                        SPStaticUtils.remove(Constants.LOGININFO)
                        mBinding.userName.text = "请登录"
                        Glide.with(this).load("").placeholder(R.mipmap.app_kuaikan).into(mBinding.userAvatar)
                        loginInfo = ""
                        userInfo = null
                        ToastUtils.showShort("退出登录成功,请重新登陆")
                    } else {
                        ToastUtils.showShort("您已退出")
                    }

                }
                mBinding.llZxzh.id->{
                    if (!ValidUtils.isValid(userInfo)){
                        ToastUtils.showShort("您未登录,无法注销账号")
                        return
                    }
                    userInfo?.let {
                        if (LitePalUtils.deleteUser(it.username)>0){
                            SPStaticUtils.remove(Constants.LOGININFO)
                            mBinding.userName.text = "请登录"
                            Glide.with(this).load("").placeholder(R.mipmap.app_kuaikan).into(mBinding.userAvatar)
                            loginInfo = ""
                            userInfo = null
                            ToastUtils.showShort("账号注销成功")
                        }else{
                            ToastUtils.showShort("账号注销失败")
                        }
                    }
                }
                mBinding.tvJl.id->{
                    if (!ValidUtils.isValid(userInfo)){
                        ToastUtils.showShort("您尚未登录")
                        return
                    }
                    ARouter.getInstance().build(RouterPath.Main.URL_Main_RecordActivity).navigation()
                }

                else -> {}
            }
        }
    }
}